package com.lht.femalecat.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Date;

/**
 * @Author:骆宏图
 * @CreateDate: 10:34 2018/7/27.
 * @Description:
 * @Modified By:
 */
public class TimeServer {

    public static void main(String[] args){
        EventLoopGroup acceptGroup=new NioEventLoopGroup();//处理接受的线程组
        EventLoopGroup proccessGroup=new NioEventLoopGroup();//处理 读写操作的线程组
        try {
            ServerBootstrap bootstrap=new ServerBootstrap();
            bootstrap.group(acceptGroup,proccessGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_BACKLOG,1024);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            ByteBuf buf=(ByteBuf)msg;
                            byte[] bytes=new byte[buf.readableBytes()];
                            buf.readBytes(bytes);
                            String content=new String(bytes,"UTF-8");
                            System.out.println("The time server recevice order:  "+content);

                            String currentTime="Query Time Order".equalsIgnoreCase(content)?new Date(System.currentTimeMillis()).toString():"Bad Order";
                            ByteBuf resp= Unpooled.copiedBuffer(currentTime.getBytes());
                            ctx.write(resp);
                        }

                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                            ctx.flush();
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//                        super.exceptionCaught(ctx, cause);
                            ctx.close();
                        }
                    });
                }
            });
            //绑定端口，同步等待成功
            ChannelFuture future=bootstrap.bind(8080).sync();
            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            //优化退出释放线程池资源
            acceptGroup.shutdownGracefully();
            proccessGroup.shutdownGracefully();
        }
    }

}
